<template>
  <div>


    <j-modal
      :title='title'
      :width='width'
      :visible='visible'
      :confirmLoading='confirmLoading'
      switchFullscreen
      @ok='handleOk'
      @cancel='handleCancel'
      cancelText='关闭'>
      <a-spin :spinning='confirmLoading'>
        <a-form :form='form'>

          <a-form-item label='基地' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <!--          <a-input v-decorator="['sourceBase']" placeholder="请输入基地"></a-input>-->
            <a-select v-decorator="['sourceBase', validatorRules.sourceBase]" placeholder='请选择所属基地'
                      @change='handleChange'>
              <a-select-option v-for='d in baseList' :key='d.id' :value='d.id'>{{ d.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label='地块' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <!--          <a-input v-decorator="['sourceGreenhouse']" placeholder="请输入地块"></a-input>-->
            <a-select v-decorator="['sourceGreenhouse', validatorRules.sourceGreenhouse]" placeholder='请选择所属大棚'>
              <a-select-option v-for='d in greenhouseList' :key='d.id' :value='d.id'>{{ d.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label='采收产品' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <div style="margin-bottom: 0px">
              <a-row style='margin-top: 0px'>
                <a-col :span='20'>
                  <div style='display: inline-block;width: 100%'>
                    <a-input v-decorator="['variety', validatorRules.variety]" placeholder="请选择产品" disabled></a-input>
                  </div>
                </a-col>

                <a-col :span='4'>
                  <a-button type='primary'   @click='openDialog'  >选择产品</a-button>
                </a-col>
              </a-row>
            </div>


<!--            <a-button type='primary' @click='openDialog'>选择产品</a-button>-->
<!--            <a-input v-decorator="['variety', validatorRules.variety]" placeholder="请输入采收产品" disabled></a-input>-->

<!--            <a-select v-decorator="['variety', validatorRules.variety]" placeholder='请选择产品' @change='varietyChange'>-->
<!--              <a-select-option v-for='(d,i) in varietyList' :itemscope='d.code' :pack='d.packingSpecifications'-->
<!--                               :leng='d.flowerPoleLength' :key='d.id' :value='d.name'>{{ d.name }}-->
<!--              </a-select-option>-->
<!--            </a-select>-->

          </a-form-item>
          <a-form-item label='商品编码' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input v-decorator="['varietyCode', validatorRules.varietyCode]" disabled='disabled'></a-input>
          </a-form-item>


          <a-form-item label='打包规格' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input v-decorator="['packingSpecifications', validatorRules.packingSpecifications]" placeholder='请输入打包规格'
                     disabled></a-input>
            <!--          <a-select   v-decorator="['packingSpecifications', validatorRules.packingSpecifications]" placeholder="请选择打包规格"  >-->
            <!--            <a-select-option v-for="(d,i) in psfList"  :key="d.id" :value="d.title">{{ d.title }}</a-select-option>-->
            <!--          </a-select>-->
          </a-form-item>
          <a-form-item label='单位' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input v-decorator="['flowerPoleLength', validatorRules.flowerPoleLength]" placeholder='请输入单位'
                     disabled></a-input>
            <!--          <a-select  v-decorator="['flowerPoleLength', validatorRules.flowerPoleLength]" placeholder="请选择单位"  >-->
            <!--            <a-select-option v-for="(d,i) in lengthList"  :key="d.id" :value="d.title">{{ d.title }}</a-select-option>-->
            <!--          </a-select>-->
          </a-form-item>
          <a-form-item label='冷库' :labelCol='labelCol' :wrapperCol='wrapperCol'>
<!--            <j-dict-select-tag type='list' v-decorator="['storehouse', validatorRules.storehouse]" :trigger-change='true'
                               dictCode='flower_storehouse,name,code' placeholder='请选择冷库' />-->

            <a-select v-decorator="['storehouse', validatorRules.storehouse]" placeholder='请选择冷库'>
              <a-select-option v-for='d in hoseList' :key='d.id' :value='d.code'>{{ d.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label='入库数量' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input-number v-decorator="['tagNum', validatorRules.tagNum]" placeholder='请输入入库数量' style='width: 100%' />
          </a-form-item>

          <!--        <a-form-item label="等级" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
          <!--          <a-select  v-decorator="['classes', validatorRules.classes]" placeholder="请选择等级"  >-->
          <!--            <a-select-option v-for="(d,i) in classesList"  :key="d.id" :value="d.title">{{ d.title }}</a-select-option>-->
          <!--          </a-select>-->
          <!--        </a-form-item>-->
          <a-form-item label='分拣日期' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <j-date placeholder='请选择分拣日期' v-decorator="['sortTime']" :trigger-change='true' style='width: 100%' />
          </a-form-item>
          <a-form-item label='创建日期' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <j-date disabled='disabled' placeholder='请选择创建日期' v-decorator="['createTime']" :trigger-change='true'
                    style='width: 100%' />
          </a-form-item>

          <a-form-item label='状态' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input v-decorator="['state']" placeholder='请输入状态（0正常，1删除）' disabled='disabled'></a-input>
          </a-form-item>
          <a-form-item label='打印标签次数' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input-number disabled='disabled' v-decorator="['printNum']" placeholder='请输入打印标签次数（0未打印，1打印，）'
                            style='width: 100%' />
          </a-form-item>
        </a-form>
      </a-spin>
    </j-modal>

    <a-modal v-model:visible='varietyVisible' width='60%' title='产品选择' >
      <div style="margin-bottom: 10px">
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block;width: 45px;'>产品：</div>
            <div style='display: inline-block;width: 70%'>
              <a-input v-model='queryVarietyParams.name' placeholder='请输入产品名称' allow-clear @change="searchFlowerVarietys"/>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;width: 80px;'>商品编码：</div>
            <div style='display: inline-block;width: 70%'>
              <a-input v-model='queryVarietyParams.code' placeholder='请输入商品编码' allow-clear @change="searchFlowerVarietys"/>
            </div>
          </a-col>
          <a-col :span='8'>
            <a-button type="primary" icon="search" @click="searchFlowerVarietys">
              查询
            </a-button>
          </a-col>
        </a-row>
      </div>
      <a-table :columns='selectVarietyColumns' :data-source='selectVarietyDataSource' bordered
               :loading='selectVarietyLoading'
               :row-selection="{selectedRowKeys: selectedRowKeys,type: 'radio',onChange:onVarietySelectChange}"
               row-key='id'
               :pagination='varietyPagination'
               @change='varietyPaginationChange'
      ></a-table>
    </a-modal>
  </div>
</template>

<script>

import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JDate from '@/components/jeecg/JDate'
import { queryFlowerBase, ajaxGetDictItems, queryGreenhouseByPd, getVarietyList ,listByPsn} from '@/api/api'
import {getFlowerVarietys} from "../../../api/api";

export default {
  name: 'FlowerTagInModal',
  components: {
    JDate
  },
  data() {
    return {
      queryVarietyParams: {// 产品选择弹窗的查询
        name: '',// 产品名称
        code: ''// 商品编码
      },
      hoseList: [], //冷库
      baseList: [], //基地信息
      greenhouseList: [], //大棚信息
      classesList: [], //等级信息
      varietyList: [], //品类信息
      psfList: [], //打包规格
      lengthList: [], //长度信息
      varietyCode: '',
      form: this.$form.createForm(this),
      title: '操作',
      width: 800,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        // packingSpecifications: {
        //   rules: [
        //     { required: true, message: '请选择打包规格!'},
        //   ]
        // },
        sourceBase: {
          rules: [
            { required: true, message: '请选择基地!' }
          ]
        }, storehouse: {
          rules: [
            { required: true, message: '请选择冷库!' }
          ]
        }, sourceGreenhouse: {
          rules: [
            { required: true, message: '请选择大棚!' }
          ]
        },/* classes: {
            rules: [
              { required: true, message: '请选择等级!'},
            ]
          },*/
        variety: {
          rules: [
            { required: true, message: '请选择采收产品!' }
          ]
        },
        varietyCode: {
          rules: [
            { required: true, message: '请选择采收产品!' }
          ]
        },
        packingSpecifications: {
          rules: [
            { required: true, message: '请选择打包规格!' }
          ]
        },
        tagNum: {
          rules: [
            { required: true, message: '请输入入库数量!' }
          ]
        },
        flowerPoleLength: {
          rules: [
            { required: true, message: '请选择单位!' }
          ]
        }
      },
      url: {
        add: '/flower/flowerTagIn/add',
        edit: '/flower/flowerTagIn/edit',
        dicUrl: '',
        getBasename: '/flower/flowerTagIn/edit'
      },
      varietyVisible: false,//是否打开产品选择的弹窗
      selectVarietyColumns: [// 第二个弹窗的表头
        {
          title: '产品',
          dataIndex: 'name'
        }, {
          title: '商品编码',
          dataIndex: 'code'
        }, {
          title: '规格',
          dataIndex: 'packingSpecifications'
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength'
        }
      ],
      selectedRowKeys:[],
      varietyLoading: true,
      selectVarietyLoading: true,
      selectVarietyDataSource: [],// 第二个弹窗中可选择的产品列表
      selectVariety: {},// 第二个弹窗中已选择的产品
      varietyPagination: {// 产品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
    }
  },
  created() {
    this.initBaseInfo()    //初始化基地信息
    this.initVarietyList()//初始化产品信息

    this.hoseList =  JSON.parse( localStorage.getItem("ch_storehouse")?localStorage.getItem("ch_storehouse"):"[]")

    // this.initClassifyDict()//初始化等级信息
    // this.initpsfDict()//初始化打包规格
    // this.initlengthDict()//
  },
  methods: {

    searchFlowerVarietys() {//根据条件查询产品选择弹窗中的产品列表
      let params = {
        name:this.queryVarietyParams.name,
        code:this.queryVarietyParams.code
      }
      getVarietyList(params).then((res) => {
        if (res.success) {
          this.varietyList = res.result
          this.selectVarietyDataSource = res.result
          this.selectVarietyLoading =false
        }
      })
    },
    varietyChange(value, itemscope) {
      // validatorRules
      if (itemscope && itemscope.data && itemscope.data.attrs && itemscope.data.attrs.itemscope) {
        this.varietyCode = itemscope.data.attrs.itemscope
        this.form.setFieldsValue({
          varietyCode: itemscope.data.attrs.itemscope
        })
      } else {
        this.varietyCode = undefined
        this.form.setFieldsValue({
          varietyCode: undefined
        })
      }

      if (itemscope && itemscope.data && itemscope.data.attrs && itemscope.data.attrs.leng) {

        this.form.setFieldsValue({
          flowerPoleLength: itemscope.data.attrs.leng
        })
      } else {
        this.form.setFieldsValue({
          flowerPoleLength: undefined
        })
      }

      if (itemscope && itemscope.data && itemscope.data.attrs && itemscope.data.attrs.pack) {
        this.form.setFieldsValue({
          packingSpecifications: itemscope.data.attrs.pack
        })
      } else {
        this.form.setFieldsValue({
          packingSpecifications: undefined
        })
      }
    },
    handleChange(value) {
      queryGreenhouseByPd(value).then((res) => {
        if (res.success) {
          this.greenhouseList = res.result
          this.form.setFieldsValue({ sourceGreenhouse: undefined })
        }
      })
    },
    handleEditChange(value) {
      queryGreenhouseByPd(value).then((res) => {
        if (res.success) {
          this.greenhouseList = res.result
        }
      })
    },
    //初始化基地信息
    initBaseInfo() {
      queryFlowerBase().then((res) => {
        if (res.success) {
          this.baseList = res.result
        }
      })
    },
    //初始化产品信息
    initVarietyList() {
      getVarietyList().then((res) => {
        if (res.success) {
          this.varietyList = res.result
          this.selectVarietyDataSource = res.result
          this.selectVarietyLoading =false
        }
      })
    },
    //初始化等级信息
    initClassifyDict() {
      const dictCode = 'planting_flower_level'
      ajaxGetDictItems(dictCode, null).then((res) => {
        if (res.success) {
          this.classesList = res.result
        }
      })
    },
    //初始化打包规格信息
    initpsfDict() {
      const dictCode = 'planting_packing_specifications'
      ajaxGetDictItems(dictCode, null).then((res) => {
        if (res.success) {
          this.psfList = res.result
        }
      })
    }, //
    initlengthDict() {
      const dictCode = 'planting_flower_pole'
      ajaxGetDictItems(dictCode, null).then((res) => {
        if (res.success) {
          this.lengthList = res.result
        }
      })
    },
    initVarietyDict() {
      const dictCode = 'planting_variety'
      ajaxGetDictItems(dictCode, null).then((res) => {
        if (res.success) {
          this.varietyList = res.result
        }
      })
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.handleEditChange(record.sourceBase)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'sourceBase', 'sourceGreenhouse', 'variety', 'classes','storehouse', 'varietyCode', 'sortTime', 'packingSpecifications', 'tagNum', 'flowerPoleLength', 'createTime', 'updateTime', 'createUser', 'updateUser', 'state', 'printNum'))
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          if(formData.tagNum<=0){
            that.$message.warning("入库数量必须大于0 ！")
            that.confirmLoading = false
          }else{
            // console.log("表单提交数据",formData)
            // formData.varietyCode = this.varietyCode
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }
        }
      })
    },
    handleCancel() {
      this.close()
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'sourceBase', 'sourceGreenhouse', 'variety', 'varietyCode', 'classes', 'storehouse', 'sortTime', 'packingSpecifications', 'tagNum', 'flowerPoleLength', 'createTime', 'updateTime', 'createUser', 'updateUser', 'state', 'printNum'))
    },
    varietyAdd() {// 第二个弹窗中的新增产品

    },
    onVarietySelectChange(selectedRowKeys, selectionRows) {

      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法单选
      this.selectionRows = selectionRows

      this.selectVariety = selectionRows[0]
    },
    varietyPaginationChange(pagination) {
      this.varietyPagination.current = pagination.current
      this.varietyPagination.pageSize = pagination.pageSize
      this.initVarietyList()

    },
    openDialog() {

      this.selectedRowKeys = []
      this.selectVariety = {}
      this.initVarietyList()
      this.varietyVisible = !this.varietyVisible
    }


  }
}
</script>
<style>
.ant-form-item {
  margin: 0;
  padding: 0;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  font-variant: tabular-nums;
  line-height: 1.5;
  list-style: none;
  font-feature-settings: 'tnum';
  margin-bottom: 6px;
  vertical-align: top;
}
</style>